import { checkIfLogin } from '../../utils/check'
import { queryOrderInfoList, receiveOrder } from '../../services/order'

Page({
  data: {
    active:'all',
    titleStyle:{
      fontSize:'40rpx'
    },
    orderList:[],
    showDialogConfirm:false,
    dialogMsg:"",
    currentItem: {},
    orderId:""
  },

  onLoad(options){
    checkIfLogin()
    if(!options){
      return
    }

    let tabIndex = ""
    tabIndex = options.tabIndex
    this.setData({
      active: tabIndex ? tabIndex : 'all'
    })
    this.checkStatus(tabIndex)
  },

  onShow(){
    checkIfLogin()
    if(this.data.active){
      this.checkStatus(this.data.active)
    }
  },
  
  handleChangeTab(event){
    let active = event.detail
    this.setData({
      active
    })
    this.checkStatus(active)
  },

  checkStatus(tabIndex){
    let status = ""
    let data = {}
    let url = "detect/order/listDetectOrder"
    if( tabIndex == 'pendingOrder' ){
      status = 1
      url = 'detect/order/list'
    } else if( tabIndex == 'toBeProcessed' ){
      status = 2
    } else if( tabIndex == 'handled' ){
      status = 3
    }

    if(status){
      data = {
        status
      }
    }
    this.getOrderList(url, data)
  },

  async getOrderList(url, data){
    let res = await queryOrderInfoList(url, data)
    if(res.code === 200){
      let orderList = res.rows
      this.setData({
        orderList
      })
    }
  },

  handleViewDetail(event){
    let currentItem = event.detail
    let id = event.detail.id
    let vehicleId = event.detail.vehicleId
    if( currentItem.status == 1 ){
      wx.navigateTo({
        url: `/pages/order-tobe/order-tobe?id=${id}`,
      })
    } else if( currentItem.status == 2 ){
      wx.navigateTo({
        url: `/pages/order-handle/order-handle?id=${id}&vehicleId=${vehicleId}`,
      })
    }
  },

  handleTakeOrder(event){
    let currentItem = event.detail
    let orderId = currentItem.id
    this.setData({
      orderId,
      showDialogConfirm:true,
      dialogMsg:"是否确认接单?",
    })
  },

  async handleConfirm(){
    let confirmRes = await receiveOrder(this.data.orderId)
    if(confirmRes.code === 200){
      wx.reLaunch({
        url: `/pages/order-take-success/order-take-success?orderId=${this.data.orderId}`,
      })
    }
  }
})